# Create your views here.
# coding=utf-8
from django.shortcuts import *
from django.contrib.auth import authenticate, login
from django.template import RequestContext, loader, Context
from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpRequest
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_protect

from hwcorp.apps.blog.models import *
from hwcorp.apps.blog.forms import *
from django.contrib.auth.decorators import login_required

def index(request):
    post_list = Post.objects.all()
    is_authenticated = request.user.is_authenticated()
    
    return render_to_response('blog/index.html', locals(), context_instance = RequestContext(request))
@csrf_protect
@login_required    
def add_new_post(request):
    if request.user.is_authenticated():
        if request.POST:
            form = PostForm(request.POST)
            if form.is_valid():
                form.save();
                return HttpResponseRedirect(reverse('blog_index'))
            
        else:
            form = PostForm()
        return render_to_response('blog/add_post.html', locals(), context_instance = RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('site_index'))
    
@login_required        
def delete_post(request):
    if request.user.is_authenticated():
        if request.POST:
            post_id = request.REQUEST.get('post_id')
            p = Post.objects.filter(id = post_id)
            if p:
                p.delete()            
            
            return HttpResponseRedirect(reverse('blog_index'))
    else:
        return HttpResponseRedirect(reverse('site_index'))
@csrf_protect
def view_post(request):
    if request.GET:
        post_id = request.REQUEST.get('post_id', '0')
        if post_id == '0':
            return HttpResponseRedirect(reverse('blog_index'))
        else:
            post_list = Post.objects.filter(id = post_id)
            if post_list:
                post = post_list[0]
                post.increase_view()
                post.save()
                comment_list = Comment.objects.filter(post = post)
                if request.POST:
                    comment_form = NewCommentForm(request.POST)
                    if comment_form.is_valid():
                        comment_form.save(post);
                        comment_form = NewCommentForm()
                else:
                    comment_form = NewCommentForm()
                return render_to_response('blog/view_post.html', locals(), context_instance = RequestContext(request))
            else:
                return HttpResponseRedirect(reverse('blog_index'))
    else:
        return HttpResponseRedirect(reverse('blog_index'))
    
